﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.ServiceModel;
using Fdd.Aspen.Infrastructure.Data;
using System.ServiceModel.DomainServices.Server;

namespace WcfRiaServices.Extensions
{
    public class UnityDomainServiceFactory : IDomainServiceFactory
    {
        private IUnityContainer _unityContainer = null;

        
        public UnityDomainServiceFactory(IUnityContainer unityContainer)
        {
            if (unityContainer == null)
                throw new ArgumentNullException("unityContainer");

            _unityContainer = unityContainer;
        }


        public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
        {
            var service = _unityContainer.Resolve(domainServiceType) as DomainService;

            if (service is ObjectContextDomainService)
                ((ObjectContextDomainService)service).Initialize(_unityContainer.Resolve<IObjectContext>(), context);
            else
                service.Initialize(context);

            return service;
        }


        public void ReleaseDomainService(DomainService domainService)
        {
            domainService.Dispose();
        }
    }
}
